const grunt = require("grunt");
class File {
  constructor(name) {
    grunt.file.defaultEncoding = "utf8";
    this.name = name;
    return this;
  }
  read() {
    return grunt.file.exists(this.name) ? grunt.file.readJSON(this.name) : null;
  }
  write(content, ops) {
    grunt.file.write(this.name, content, ops || {});
    return this;
  }
  delete() {
    if (grunt.file.exists(this.name)) grunt.file.delete(this.name);
    return this;
  }
}
const file = new File("./src/data/store.json");
let storeData = {};
class Store {
  constructor() {
    this.state = {};
    let _state = file.read();
    if (_state) {
      this.state = { ...this.state, ..._state };
      file.write(JSON.stringify(this.state));
    }
    return this;
  }
  createStore(ops) {
    this.state = { ...this.state, ...(ops.state || {}) };
    file.write(JSON.stringify(this.state));
    storeData._actions = ops.actions;
    storeData._mutations = ops.mutations;
    storeData._getters = ops.getters;
    return this;
  }
  setState(name, value) {
    this.state[name] = value;
    file.write(JSON.stringify(this.state));
    return this.state[name];
  }
  query(filter, target) {
    target = target || this.state;
    if (!filter) return;
    let filterResult = [];
    for (let n in target) {
      if (typeof filter === "function") {
        let res = filter(target[n]);
        if (res) {
          filterResult.push(target[n]);
        }
      } else if (target[n] === filter) {
        filterResult.push(target[n]);
      }
    }
    return filterResult;
  }
  destroy() {
    this.state = {};
    file.delete();
  }
  computed() {
    let args = arguments,
      that = this;
    return storeData._getters[args[0]](that.state, that);
  }
  dispatch() {
    let args = arguments,
      that = this;
    return new Promise((resolve, reject) => {
      if (args[0]) {
        storeData._actions[args[0]](that, args[1])
          .then((res) => resolve(res))
          .catch((err) => reject(err));
      } else {
        reject();
      }
    });
  }
  commit() {
    let args = arguments,
      that = this;
    return new Promise((resolve, reject) => {
      if (args[0]) {
        storeData._mutations[args[0]](that, args[1]);
        resolve();
      } else {
        reject();
      }
    });
  }
}
module.exports = Store;
